package com.cn.longdistancebusstation.ui;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import com.cn.longdistancebusstation.R;
import com.cn.longdistancebusstation.adapter.StationAdapter;
import com.cn.longdistancebusstation.city.CharacterParser;
import com.cn.longdistancebusstation.city.ClearEditText;
import com.cn.longdistancebusstation.city.PinyinComparator;
import com.cn.longdistancebusstation.city.SideBar;
import com.cn.longdistancebusstation.base.BaseActivity;
import com.cn.longdistancebusstation.httpHelper.HttpHelper;
import com.cn.longdistancebusstation.httpapi.WebService;
import com.cn.longdistancebusstation.model.Station;
import com.cn.longdistancebusstation.view.StationNameListView;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

/**
 * Created by mucheng on 2018/1/30.
 */

public class DestinationActivity extends BaseActivity implements View.OnClickListener{
    private ImageView mBackImageView;
    private ClearEditText et;
    private StationNameListView mStationNameListView;
    private StationAdapter mStationAdapter;
    private List<Station> list;
    private TextView mDialogTextView;
    private SideBar sideBar;
    private String mdestination;
    private List<String> mStationList;
    /**
     * 汉字转换成拼音的类
     */
    private CharacterParser characterParser;
    /**
     * 根据拼音来排列ListView里面的数据类
     */
    private PinyinComparator pinyinComparator;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_city_main);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        initView();
    }

    private void initView() {
        mBackImageView=(ImageView)findViewById(R.id.back);
        mBackImageView.setOnClickListener(this);
        et=(ClearEditText)findViewById(R.id.filter_edit);
        et.setOnClickListener(this);
        mDialogTextView = (TextView) findViewById(R.id.dialog);
        sideBar = (SideBar) findViewById(R.id.sidrbar);
        sideBar.setTextView(mDialogTextView);
        mStationNameListView=(StationNameListView)findViewById(R.id.country_lvcountry);
        mStationNameListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

            }
        });
        //设置右侧触摸监听
        sideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {

            @Override
            public void onTouchingLetterChanged(String s) {
                //该字母首次出现的位置
                int position = mStationAdapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    mStationNameListView.setSelection(position);
                }

            }
        });

        mStationNameListView = (StationNameListView) findViewById(R.id.country_lvcountry);
        mStationNameListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                //这里要利用adapter.getItem(position)来获取当前position所对应的对象
                mdestination=((Station) mStationAdapter.getItem(position)).getStationName();
                SharedPreferences.Editor editor=getSharedPreferences("data",MODE_PRIVATE).edit();
                editor.putString("destination",mdestination);
                editor.apply();
                Log.d("目的地",mdestination);
//                Toast.makeText(getApplication(), ((SortModel) adapter.getItem(position)).getName(), Toast.LENGTH_SHORT).show();
            }
        });
        et = (ClearEditText) findViewById(R.id.filter_edit);

        //根据输入框输入值的改变来过滤搜索
        et.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        getDesPorts();
        list=new ArrayList<>();
        mStationList=new ArrayList<>();
        for(int i=0;i<mStationList.size();i++){
            Station station_name=new Station();
            station_name.setStationName(mStationList.get(i));
            list.add(station_name);
            String pinyin = characterParser.getSelling(mStationList.get(i));
            String sortString = pinyin.substring(0, 1).toUpperCase();

            // 正则表达式，判断首字母是否是英文字母
            if (sortString.matches("[A-Z]")) {
                station_name.setStationCode(sortString.toUpperCase());
            } else {
                station_name.setStationCode("#");
            }

            list.add(station_name);

        }
        mStationAdapter=new StationAdapter(this,list);
        mStationNameListView.setAdapter(mStationAdapter);
        mStationAdapter.notifyDataSetChanged();
    }
    private void getDesPorts() {
        Retrofit retrofit = new HttpHelper.WebServiceBuilder().build().getRetrofit();
        WebService webService = retrofit.create(WebService.class);
        Call<String> call = webService.getDesPorts();
        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                try
                {
                    Log.i("ParseXMLActivity", response.body());
                    parseXMLForDesPorts(response.body());
                    mStationList.add(response.body());
                    Log.d("城市",mStationList.add(response.body())+"");

                }
                catch(XmlPullParserException e)
                {}
                catch(IOException e)
                {}
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {

            }
        });
    }
    private void parseXMLForDesPorts(String xmlText) throws XmlPullParserException,IOException {
        list.clear();
        XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
        factory.setNamespaceAware(true);
        XmlPullParser xmlPullParser = factory.newPullParser();
        xmlPullParser.setInput(new StringReader(xmlText));
        mStationList.add(xmlText);
        Log.d("我的数据",mStationList.add(xmlText)+"");
        int eventType = xmlPullParser.getEventType();
        String strTagName = "";
        Station station = null;
        while(eventType != XmlPullParser.END_DOCUMENT){
            if(eventType == XmlPullParser.START_DOCUMENT)
            {}
            else if(eventType == XmlPullParser.START_TAG)
            {
                strTagName = xmlPullParser.getName();
                if(strTagName.equals("portList"))
                {
                    station = new Station();
                }
            }
            else if(eventType == XmlPullParser.END_TAG)
            {
                strTagName = "";
                if(xmlPullParser.getName().equals("portList"))
                {
                    list.add(station);


                }
            }
            else if(eventType == XmlPullParser.TEXT)
            {
                if(strTagName.equals("PortID"))
                {
                    station.setStationID(xmlPullParser.getText());
                }
                else if(strTagName.equals("PortName"))
                {
                   station.setStationName(xmlPullParser.getText());

                }
                else if(strTagName.equals("PortCode"))
                {
                    station.setStationCode(xmlPullParser.getText());
                }
            }
            eventType = xmlPullParser.next();
        }
    }
    /**
     * 根据输入框中的值来过滤数据并更新ListView
     *
     * @param filterStr
     */
    private void filterData(String filterStr) {
        List<Station> filterDateList = new ArrayList<Station>();

        if (TextUtils.isEmpty(filterStr)) {
            filterDateList = list;
        } else {
            filterDateList.clear();
            for (Station sortModel : list) {
                String name = sortModel.getStationName();
                if (name.indexOf(filterStr.toString()) != -1 || characterParser.getSelling(name).startsWith(filterStr.toString())) {
                    filterDateList.add(sortModel);
                }
            }
        }

        Collections.sort(filterDateList, pinyinComparator);
        mStationAdapter.updateListView(filterDateList);
    }


    @Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.back:
                Intent intent = getIntent();
                intent.putExtra("destination", mdestination);
                setResult(2, intent);
                finish();
                break;
        }

    }
}
